﻿using Microsoft.AspNetCore.Authorization;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Localization;
using Volo.Abp.TextTemplateManagement.Authorization;
using Volo.Abp.TextTemplating;

namespace Volo.Abp.TextTemplateManagement.TextTemplates
{
    [Authorize(TextTemplateManagementPermissions.TextTemplates.Default)]
	public class TemplateDefinitionAppService : TextTemplateManagementAppServiceBase, IRemoteService, IApplicationService, ITemplateDefinitionAppService
	{

		private readonly ITemplateDefinitionManager _templateDefinitionManager;

		public TemplateDefinitionAppService(ITemplateDefinitionManager templateDefinitionManager)
		{
			this._templateDefinitionManager = templateDefinitionManager;
		}

		public virtual Task<PagedResultDto<TemplateDefinitionDto>> GetListAsync(GetTemplateDefinitionListInput input)
		{
			var all = this._templateDefinitionManager.GetAll();
			var list = new List<TemplateDefinitionDto>();
			foreach (var templateDefinition in all)
			{
				var templateDefinitionDto = base.ObjectMapper.Map<TemplateDefinition, TemplateDefinitionDto>(templateDefinition);
				templateDefinitionDto.DisplayName = templateDefinition.GetLocalizedDisplayName(base.StringLocalizerFactory, "DisplayName:");
				list.Add(templateDefinitionDto);
			}
			if (!string.IsNullOrWhiteSpace(input.FilterText))
			{
				input.FilterText = input.FilterText.ToUpper();
				list = (from x in list
				where (x.DisplayName != null && x.DisplayName.ToUpper().Contains(input.FilterText)) || x.Name.ToUpper().Contains(input.FilterText) || (x.DefaultCultureName != null && x.DefaultCultureName.Contains(input.FilterText))
				select x).ToList<TemplateDefinitionDto>();
			}
			long count = (long)list.Count;
			list = list.Skip(input.SkipCount).Take(input.MaxResultCount).ToList<TemplateDefinitionDto>();
			return Task.FromResult<PagedResultDto<TemplateDefinitionDto>>(new PagedResultDto<TemplateDefinitionDto>(count, list));
		}

		public virtual Task<TemplateDefinitionDto> GetAsync(string name)
		{
			var templateDefinition = this._templateDefinitionManager.Get(name);
			var templateDefinitionDto = base.ObjectMapper.Map<TemplateDefinition, TemplateDefinitionDto>(templateDefinition);
			templateDefinitionDto.DisplayName = templateDefinition.GetLocalizedDisplayName(base.StringLocalizerFactory, "DisplayName:");
			return Task.FromResult<TemplateDefinitionDto>(templateDefinitionDto);
		}
	}
}
